<template>
  <div >
    <el-breadcrumb v-if="model" separator-class="el-icon-arrow-right" style="margin-bottom: 15px;font-size: 20px;">
      <el-breadcrumb-item v-for="dir in dirList">
        <template slot-scope="scope"><a style="cursor:pointer; color:black" @click="getFileList(dir)">{{dir.name}}</a>
        </template>
      </el-breadcrumb-item>
    </el-breadcrumb>
    <h2 style="text-align: left;margin-top: -7px;" v-else="model">搜索结果：{{keyword}}</h2>
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="searchFile" style="float:left">
      <el-form-item>
        <el-input size="small" v-model="keyword" placeholder="输入关键字" prefix-icon="el-icon-search" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="searchFile" size="small" type="success" >搜索</el-button>
        <el-button @click="returnComm" size="small" type="info" >重置</el-button>
      </el-form-item>
    </el-form>
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getFileList()" style="float:right;">

      <el-form-item >
        <el-button  v-if="userName === 'admin'" type="warning" size="small" @click="format">格式化</el-button>
        <el-button  type="success" size="small" @click="enterDiskInfo">硬盘详情</el-button>
        <el-button  type="primary" size="small" @click="createFile">创建文件</el-button>
        <el-button  type="danger" size="small" @click="deleteAll()" :disabled="fileListSelections.length <= 0">批量删除</el-button>
      </el-form-item>
    </el-form>

    <el-table
      :data="fileList"
      v-loading="fileListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%;"

      :cell-style="{paddingTop:'10px',paddingBottom:'10px'}"
      >
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50"
      >
      </el-table-column>
      <el-table-column
        header-align="left"
        align="left"
        width="300"
        label="文件名">
        <template slot-scope="scope">
          <i :class="scope.row.type == 0 ? 'el-icon-tickets':'el-icon-message'"
          style="font-size: 20px;"></i>
          <a style="cursor:pointer; color:black" @click="clickName(scope.row)">{{scope.row.name}}</a>
        </template>
      </el-table-column>
      <el-table-column
        header-align="center"
        align="center"
        label="文件大小">
        <template slot-scope="scope">
          {{scope.row.length*64}}KB
        </template>
      </el-table-column>
      <el-table-column
        prop="username"
        header-align="center"
        align="center"
        label="创建人">
      </el-table-column>
      <!--      <el-table-column-->
      <!--        prop="createTime"-->
      <!--        header-align="center"-->
      <!--        align="center"-->
      <!--        width="180"-->
      <!--        label="创建时间">-->
      <!--      </el-table-column>-->
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="300"
        label="操作">
        <template slot-scope="scope">
          <el-button  type="primary" plain size="small" @click="showFileInfo(scope.row)">文件信息</el-button>
          <el-button  type="success" plain size="small" @click="enterFile(scope.row)">编辑</el-button>
          <el-button  type="danger" plain size="small" @click="deleteOne(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 弹窗, 新增 / 修改 -->
    <fileInfo v-if="fileInfoVisible" ref='showFile' @refreshFileList="getFileList(currDir)"></fileInfo>
    <addFile v-if="addFileVisible" ref='addFile' @refreshFileList="getFileList(currDir)"></addFile>

  </div>
</template>

<script>
   import fileInfo from './fileInfo'
   import addFile from './addFile'
  export default {
    data () {
      return {
        dataForm: {
          roleName: ''
        },
        currId: 2,
        //fileList: [{"id":5828374171256274,"parent_id":3236793366352572,"name":"Jessica Moore","attribute":"a","user_id":5133935585262636,"username":"钱娜","createTime":"1992-12-05 18:23:10","updateTime":"2001-12-03 16:46:18","length":4461513053900218}],
        fileList:[],
        dirList:[{
          id: 2,
          name: 'root'
        }],
        currDir:{},
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        fileListLoading: false,
        fileListSelections: [],
        fileInfoVisible: false,
        addFileVisible: false,
        keyword:'',
        model:true,   //true为普通模式  false为搜索模式
      }
    },
    components: {
       fileInfo,
       addFile
    },
    watch:{
    },
    mounted(){
      this.getFileList()
    },
    activated () {
      //init
    },
    computed:{
      mainTabsActiveName: {
        get () { return this.$store.state.common.mainTabsActiveName },
        set (val) { this.$store.commit('common/updateMainTabsActiveName', val) }
      },
      mainTabs: {
        get () { return this.$store.state.common.mainTabs },
        set (val) { this.$store.commit('common/updateMainTabs', val) }
      },
      userName: {
        get () { return this.$store.state.user.name }
      }
    },
    methods: {
      format(){
        this.fileListLoading = true;
        this.$http({
          url: this.$http.adornUrl('/file/format'),
          method: 'post',
        }).then(({data}) => {
          if (data && data.code === 200) {
            this.$message({
              message: "格式化成功",
              type: 'success',
              duration: 1000
            });
            this.getFileList();
          }
          this.fileListLoading = false;
        })
      },
      // 获取数据列表
      getFileList (dir={id : 2,name:'root'}) {
        console.log("getFileList");
        this.fileListLoading = true;
        this.$http({
          url: this.$http.adornUrl('/file/p'),
          method: 'get',
          params: this.$http.adornParams({
            fid: dir.id,
            //keyword: this.keyword
          })
        }).then(({data}) => {
          console.log(data);
          if (data && data.code === 200) {
            console.log("success");
            this.currId = dir.id;
            this.currDir = dir;
            this.fileList = data.data.fileList;
            this.fileList.sort((a,b)=>{return b.type-a.type;});
            this.updateDirList(dir);
          } else {
            this.fileList = [];
          }
          this.fileListLoading = false
          this.model = true;
          this.keyword='';
        })
      },
      updateDirList(dir){
         for(var item of this.dirList){
           if(item.id == dir.id){
             let index = this.dirList.indexOf(item);
             this.dirList.splice(index+1,this.dirList.length-index);
             break;
           }
        }
      },
      clickName(file){
        console.log("filename:"+file.name);
        console.log("filetype:"+file.type);
        if(file.type == 1){
          this.enterDir(file);
        }else{
          this.enterFile(file);
        }
      },
      test(){
        this.updateDirList({id:4,name:'yefei'});
      },
      // 多选
      selectionChangeHandle (val) {
        this.fileListSelections = val
      },
      // 新增 / 修改
      addOrUpdateHandle (id) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id)
        })
      },
      //进入文件夹
      enterDir(dir){
        this.getFileList(dir);
        this.dirList.push(dir);
        console.log("enter dir")
      },
      //进入文件
      enterFile(file){
        console.log("enter file");
        if(file.type == 1){
          this.$message({
            message: "无法编辑目录！",
            type: 'warning',
            duration: 1000
          });
          return;
        }
        this.routeHandle(file);
        this.$router.push({
          name: 'fileContent',
          params: {
            file:file,
            type:0,
          }
        })
      },
      //进入硬盘详情
      enterDiskInfo(){
        this.$router.push({
          name: 'diskInfo',
        })
      },
      //查看文件信息
      showFileInfo(file){
        this.fileInfoVisible = true;
        let fileName = [];
        let nameList = [];
        for(var item of this.dirList){
          nameList.push(item.name);
        }
        nameList.push(file.name);
        file.location = nameList.join(' / ');
        setTimeout(()=>{this.$refs.showFile.init(file)},10);
        console.log("show");
      },
      createFile(){
        if(this.fileList.length>=8){
          this.$message({
            message: "无法创建，一个目录最多有8个项目",
            type: 'error',
            duration: 1000
          });
          return;
        }

        this.addFileVisible = true;
        setTimeout(()=>{this.$refs.addFile.init(this.currDir)},10);
      },
      deleteOne(file){
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/file'),
            method: 'delete',
            data: this.$http.adornData({
              fid: this.currDir.id,
              namelist: file.name
            })
          }).
          then(({data}) => {
            if (data && data.code === 200) {
              this.$message({
                message: '删除成功',
                type: 'success',
                duration: 1000
              });
              this.getFileList(this.currDir);
            }else{
              this.$message({
                message: '删除失败',
                type: 'error',
                duration: 1000
              });
            }
            this.fileListLoading = false;
          });
        })

      },
      deleteAll(){
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.fileListLoading=true;
          console.log(this.fileListSelections);
          let nameList = [];
          for(var item of this.fileListSelections){
            nameList.push(item.name);
          }
          this.$http({
            url: this.$http.adornUrl('/file'),
            method: 'delete',
            data: this.$http.adornData({
              fid: this.currDir.id,
              namelist: nameList.join(',')
            })
          }).then(({data}) => {
            if (data && data.code === 200) {
              this.$message({
                message: '删除成功',
                type: 'success',
                duration: 1000
              });
              this.getFileList(this.currDir);
            }else{
              this.$message({
                message: '删除失败',
                type: 'error',
                duration: 1000
              });
            }
            this.fileListLoading = false;
          });
        })

      },
      //调整Tabs
      routeHandle(file){
        // tab选中, 不存在先添加
        var tab = this.mainTabs.filter(item => item.menuId === file.parentId+"/"+file.name)[0]
        if (!tab) {
          tab = {
            menuId: file.parentId+"/"+file.name,
            name: file.name,
            title: file.name,
            type: 'module',
            iframeUrl: 'text',
            params: {type:1,file:file},
            query: {}
          }
          //tab = this.$cloneDeep(tab);
          this.mainTabs = this.mainTabs.concat(tab)
        }
        this.mainTabsActiveName = tab.name
      },
      //搜索
      searchFile(){
        console.log("getFileList");
        this.fileListLoading = true;
        this.$http({
          url: this.$http.adornUrl('/file'),
          method: 'get',
          params: this.$http.adornParams({
            keyword: this.keyword
          })
        }).then(({data}) => {
          console.log(data);
          if (data && data.code === 200) {
            console.log("success");
            this.fileList = data.data.fileList;
            this.fileList.sort((a,b)=>{return b.type-a.type;});
          } else {
            this.fileList = [];
          }
          this.fileListLoading = false;
          this.model = false;
        })
      },
      returnComm(){
        this.getFileList(this.currDir);
      }
    }
  }
</script>

<style scoped>
  .icon-warp{
    font-size: 20px;
  }
</style>
